package com.xuecheng.search.listener;

import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.CourseBaseDto;
import com.xuecheng.search.service.SearchService;
import com.xuecheng.web.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component // 课程发布监听器
@Slf4j
public class CoursePubListener {

    @Autowired
    private SearchService searchService;


    // 监听课程下架
    @RabbitListener(bindings = @QueueBinding( // 绑定
            value = @Queue("offline.queue"),  // 创建队列
            exchange =@Exchange(value = "content-exchange",type = ExchangeTypes.TOPIC), // 创建交换机
            key = "offline.pub" // routingKey

    ))
    public void listenofflinePubId(Long coursePubId){
        log.info("课程下架id：{}", coursePubId);
        // 数据同步
        try {
            searchService.offline(coursePubId);
        } catch (Exception e) {
            log.info("课程下架id：{}", coursePubId);
            throw new BusinessException(ErrorCode.COURSEPUBSHRRROR);  // 后期使用补偿机制 定时任务
        }
    }
    // 监听课程发布
    @RabbitListener(bindings = @QueueBinding( // 绑定
            value = @Queue("content.queue"),  // 创建队列
            exchange =@Exchange(value = "content-exchange",type = ExchangeTypes.TOPIC), // 创建交换机
            key = "course.pub" // routingKey

    ))
    public void listenCoursePubId(Long coursePubId){
        log.info("课程发布id：{}", coursePubId);
        // 数据同步
        try {
            searchService.MysqlToES(coursePubId);
        } catch (Exception e) {
            log.info("课程发布id：{}", coursePubId);
            throw new BusinessException(ErrorCode.COURSEPUBSHRRROR);  // 后期使用补偿机制 定时任务
        }
    }

}